<script setup>
    import {
        User,
        Lock,
        Phone,
        ChatDotRound
    } from '@element-plus/icons-vue'
    import {
        ref
    } from 'vue'
    import {
        ElMessage
    } from "element-plus";
    //控制注册与登录表单的显示， 默认显示注册
    const isRegister = ref(false);
    const rememberMe = ref(false);
    const registerData = ref({
        adminName: '',
        adminPassword: '',
        repassword: '',
        adminPhone:''
    })
    //校验密码的函数
    const checkRePassword = (rule, value, callback) => {
        if (value === '') {
            callback(new Error('请再次确认密码'))
        } else if (value !== registerData.value.adminPassword) {
            callback(new Error('请确保两次输入的密码一致'))
        } else {
            callback()
        }
    }
    //定义表单校验规则
    const rules = {
        adminName: [{
            required: true,
            message: '请输入用户名',
            trigger: 'blur'
        }],
        adminPassword: [{
            required: true,
            message: '密码不能为空',
            trigger: 'blur'
        }],
        repassword: [{
            validator: checkRePassword,
            trigger: 'blur'
        }],
        adminEmail: [{
        required: true,
        message: '请输入邮箱',
        trigger: 'blur'
        },
        {
        type: 'email',
        message: '请输入有效的邮箱地址',
        trigger: ['blur', 'change']
        }
        ],
        adminPhone: [{
        required: true,
        message: '请输入手机号',
        trigger: 'blur'
      },
      {
        pattern: /^1[34578]\d{9}$/,
        message: '请输入有效的手机号',
        trigger: ['blur', 'change']
      }
    ]
    }

    //调用后台接口，完成注册
    import {
        adminLoginService,
        sendCodeService,
        adminForgetPassService
    } from '@/api/admin.js'
    import {
        studentLoginService,
        studentForgetPassService
    } from '@/api/student.js'
    import {
        teacherLoginService,
        teacherForgetPassService
    } from '@/api/teacher.js'
    //登录函数
    import {
        useRouter
    } from 'vue-router'
    import {
        useTokenStore
    } from '@/stores/token.js'
    const router = useRouter();
    const tokenStore = useTokenStore();
    const radio = ref('admin');
    const login = async () => {
        if (rememberMe.value && radio.value==='admin') {
                localStorage.setItem('adminUserName', registerData.value.adminName);
                localStorage.setItem('adminPassword', registerData.value.adminPassword);
            }else if(rememberMe.value && radio.value === 'teacher'){
                localStorage.setItem('teacherUserName', registerData.value.adminName);
                localStorage.setItem('teacherPassword', registerData.value.adminPassword);
            }else if(rememberMe.value&& radio.value === 'student'){
                localStorage.setItem('studentUserName', registerData.value.adminName);
                localStorage.setItem('studentPassword', registerData.value.adminPassword);
            }else {
                localStorage.removeItem('username');
                localStorage.removeItem('password');
            }
        if(radio.value === 'admin'){
            //调用接口，完成登录
            let result = await adminLoginService(registerData.value)
            if (result.code === 1) {
                ElMessage.success('登录成功')
                //把得到的token存储在pinia中
                tokenStore.setToken(result.data)
                //跳转到首页，路由完成跳转
                router.push('/adminsys')
            } else {
                ElMessage.error(result.msg)
            }
        }else if(radio.value ==='teacher'){
            //调用接口，完成登录
            let result = await teacherLoginService(registerData.value)
            if (result.code === 1) {
                ElMessage.success('登录成功')
                //把得到的token存储在pinia中
                tokenStore.setToken(result.data)
                //跳转到首页，路由完成跳转
                router.push('/teachersys')
            } else {
                ElMessage.error(result.msg)
            }
        }else{
            //调用接口，完成登录
            let result = await studentLoginService(registerData.value)
            if (result.code === 1) {
                ElMessage.success('登录成功')
                //把得到的token存储在pinia中
                tokenStore.setToken(result.data)
                //跳转到首页，路由完成跳转
                router.push('/studentsys')
            } else {
                ElMessage.error(result.msg)
            }
        }
    }

    if (localStorage.getItem('adminUserName') && localStorage.getItem('adminPassword') &&radio.value ==='admin') {
        registerData.value.adminName = localStorage.getItem('adminUserName');
        registerData.value.adminPassword = localStorage.getItem('adminPassword');
        radio.value = 'admin';
        rememberMe.value = true;
    }
    const remember = async()=>{
        if (localStorage.getItem('adminUserName') && localStorage.getItem('adminPassword') &&radio.value ==='admin') {
        registerData.value.adminName = localStorage.getItem('adminUserName');
        registerData.value.adminPassword = localStorage.getItem('adminPassword');
        radio.value = 'admin';
        rememberMe.value = true;
    }else if(localStorage.getItem('teacherUserName') && localStorage.getItem('teacherPassword') && radio.value ==='teacher'){
        registerData.value.adminName = localStorage.getItem('teacherUserName');
        registerData.value.adminPassword = localStorage.getItem('teacherPassword');
        radio.value = 'teacher';
        rememberMe.value = true;
    }else if(localStorage.getItem('studentUserName') && localStorage.getItem('studentPassword') && radio.value ==='student'){
        registerData.value.adminName = localStorage.getItem('studentUserName');
        registerData.value.adminPassword = localStorage.getItem('studentPassword');
        radio.value = 'student';
        rememberMe.value = true;
    }
    }
    
const passwordVisible = ref(false);
const forgetData=ref({
    phone:'',
    pass:'',
    repass:'',
    verify:''
})
const phoneRules = [
  { required: true, message: '手机号不能为空', trigger: 'blur' },
  {
        pattern: /^1[34578]\d{9}$/,
        message: '请输入有效的手机号',
        trigger: ['blur', 'change']
 }
];
const codeRules =[
    {required:true,message:'验证码不能为空',trigger:'blur'}
]
const passwordRules = [
  { required: true, message: '密码不能为空', trigger: 'blur' }
];

const repasswordRules = [
  { required: true, message: '重复密码不能为空', trigger: 'blur' },
  { validator: checkRePassword, trigger: 'blur' }
];
const sendCode=async()=>{
    let result=await sendCodeService(forgetData.value.phone);
    if(result.code===1){
        ElMessage.success("发送成功");
        getCode();
    }else{
        ElMessage.error(result.msg);
    }
}

const updateRepass=async()=>{
    const result=ref();
    if(forgetRadio.value==='admin'){
        result.value =await adminForgetPassService(forgetData.value.phone,forgetData.value.pass,forgetData.value.verify);
    }else if(forgetRadio.value==='teacher'){
        result.value =await teacherForgetPassService(forgetData.value.phone,forgetData.value.pass,forgetData.value.verify);
    }else {
        result.value =await studentForgetPassService(forgetData.value.phone,forgetData.value.pass,forgetData.value.verify);
    }
    if(result.value.code===1){
        ElMessage.success("重置成功");
        passwordVisible.value=false;
    }else{
        ElMessage.error(result.value.msg);
    }

}
const disableBtn = ref(false); // 按钮是否禁用
const btnText = ref('获取验证码'); // 按钮文本
const getCode = () => {
  // 禁用按钮
  disableBtn.value = true;
  // 修改按钮文本
  btnText.value = '60秒后重新获取';
  
  let countDown = 60; // 倒计时时长

  const timer = setInterval(() => {
    countDown--;
    btnText.value = `${countDown}秒后重新获取`;
    if (countDown === 0) {
      clearInterval(timer); // 清除计时器
      btnText.value = '获取验证码';
      disableBtn.value = false; // 启用按钮
    }
  }, 1000);
}

const forgetRadio=ref('admin')
</script>

<template>
    <el-row class="login-page">
        <el-col :span="16" class="bg">
            <video src="@/assets/back.mp4" autoplay loop muted ></video>
        </el-col>
        <el-col :span="5" :offset="2" class="form">
            <!-- 登录表单 -->
            <el-form ref="form" size="large" autocomplete="off" :model="registerData" :rules="rules">
                <el-form-item>
                    <h1>登录</h1>
                </el-form-item>
                <el-form-item>
                    <el-radio-group v-model="radio" @change="remember">
                        <el-radio-button label="admin" value="admin" />
                        <el-radio-button label="teacher" value="teacher" />
                        <el-radio-button label="student" value="student" />
                     </el-radio-group>
                </el-form-item>
                <el-form-item prop="adminName">
                    <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="registerData.adminName"></el-input>
                </el-form-item>
                <el-form-item prop="adminPassword">
                    <el-input name="password" :prefix-icon="Lock" type="password" placeholder="请输入密码"
                        v-model="registerData.adminPassword"></el-input>
                </el-form-item>
                <el-form-item class="flex">
                    <div class="flex">
                        <el-checkbox id="rememberMe" v-model="rememberMe">记住我</el-checkbox>
                        <el-link type="primary" :underline="false" @click="passwordVisible=true">忘记密码？</el-link>
                    </div>
                </el-form-item>
                <!-- 登录按钮 -->
                <el-form-item>
                    <el-button class="button" type="primary" auto-insert-space @click="login">登录</el-button>
                </el-form-item>
            </el-form>
        </el-col>
    </el-row>
                <!-- 密码弹窗 -->
            <el-dialog v-model="passwordVisible" width="30%" :top="'calc(200px)'">
                <el-form :model="forgetData" label-width="100px" style="padding-right: 30px">
                    <el-form-item>
                        <el-radio-group v-model="forgetRadio">
                            <el-radio-button label="admin" value="admin" />
                            <el-radio-button label="teacher" value="teacher" />
                            <el-radio-button label="student" value="student" />
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item prop="phone" label="手机:" :rules="phoneRules">
                        <el-input type="phone" placeholder="请输入手机号" v-model="forgetData.phone"></el-input>
                    </el-form-item>
                    <el-form-item prop="verify" label="验证码:" :rules="codeRules" style="display: flex; align-items: center;">
                        <el-input type="email" placeholder="请输入验证码" v-model="forgetData.verify" style="width: 140px;margin-right: 10px;"></el-input>
                        <el-button :disabled="disableBtn" @click="sendCode" type="primary" plain>{{ btnText }}</el-button>
                    </el-form-item>
                    <el-form-item prop="pass" label="密码:" :rules="passwordRules">
                        <el-input type="password" placeholder="请重置密码" v-model="forgetData.pass"></el-input>
                    </el-form-item>
                    <el-form-item prop="repass" label="重复密码:" :rules="repasswordRules">
                        <el-input type="password" placeholder="请输入再次密码" v-model="forgetData.repass"></el-input>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="updateRepass" type="primary">确定</el-button>
                    </span>
                </template>
            </el-dialog>
</template>

<style lang="scss" scoped>
    /* 样式 */
    .login-page {
        height: 100vh;
        background-color: #fff;
        h1{
            font-family:'Trebuchet MS', 'Lucida Sans Unicode', 'Lucida Grande', 'Lucida Sans', Arial, sans-serif
        }
        .bg {
            //background: url('@/assets/lamp.jpeg') no-repeat center/cover;
            // no-repeat 60% center / 240px auto,
            //     url('@/assets/login_bg.jpg') no-repeat center / cover
            border-radius: 0 20px 20px 0;
            video {
                width: 100%;
                height: 100%;
                object-fit: cover; /* 视频填充容器 */
            }
        }

        .form {
            display: flex;
            flex-direction: column;
            justify-content: center;
            user-select: none;
            width: 100%;
            .title {
                margin: 0 auto;
            }

            .button {
                width: 100%;
            }

            .flex {
                width: 100%;
                display: flex;
                justify-content: space-between;
            }
        }
    }
</style>